﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Collections;
using System.ComponentModel;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Text;
using System.Transactions;
using WebServiceSmart.Router;
using Thrift.Transport;
using Thrift.Protocol;
using Thrift.Route;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using log4net;
using System.Security.Cryptography;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
using WebServiceSmart.Model;

namespace WebServiceSmart
{
    public partial class MyService
    {
        private static string baseurl = "https://openapi.tf56.com/service/api";
        private static string BIAOZHIFUAMOUNT = "biaozhifuamountrecord";
        private static string BIAOZHIFUCOMPANY = "zhifucompanybiao";

        private static int CHAXUNTIME = 60; //定时查询时间长。秒

        #region 手机操作接口

        #region 聚合支付
        //聚合支付-加密
        [WebMethod(Description = "正式版本")]
        public string ToMultiPay(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            string liushuinumber = "";
            try
            {
                logJieKou.Info("聚合支付-" + "kaishi ");
                string companyaccount = comrcv.Map_Args["companyaccount"];
                string openid = comrcv.Map_Args["openid"];
                logJieKou.Info("聚合支付-" + companyaccount);
                mainsql.openYongHuServicesql();
                #region 获取公司配置信息
                string sqlcmd = string.Format("SELECT * from {0} where com_account='{1}' ;", BIAOZHIFUCOMPANY, companyaccount);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "公司信息获取失败";  //参数错误
                    goto EXIT;
                }
                mainsql.closesql();

                DataRow dr = ds.Rows[0];
                companyaccount = dr["com_account"].ToString();
                string companynumber = dr["com_number"].ToString();
                string companyname = dr["com_name"].ToString();
                string com_appid = dr["com_appid"].ToString();
                string nodeAddr = dr["com_serviceaddr"].ToString();
                string appid = dr["com_chappid"].ToString();
                string sk = dr["com_chsk"].ToString();
                string com_accountnumber = dr["com_accountnumber"].ToString();
                #endregion

                string paytime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                liushuinumber = companynumber + DateTime.Now.ToString("yyMMddHHmmssfff");
                string jine = comrcv.Map_Args["cost"]; //金额

                #region 调用传化接口
                string logip = "";
                try
                {
                    logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
                }
                catch
                { }
                String service_id = "tf56pay.gateway.multiPay";
                Dictionary<string, object> paramMap = new Dictionary<string, object>();
                //公共参数
                paramMap.Add("appid", appid);
                paramMap.Add("tf_timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
                paramMap.Add("service_id", service_id);
                paramMap.Add("sign_type", "MD5");
                paramMap.Add("terminal", "PC");
                paramMap.Add("backurl", "https://www.q5688.com:10467/MyService.asmx/ToMultiPayHui");
                paramMap.Add("fronturl", "http://www.q5688.com");
                paramMap.Add("subject", "测试商品名称");
                paramMap.Add("businesstype", "商家消费");
                paramMap.Add("kind", "商业服务消费");
                paramMap.Add("description", "测试支付");
                paramMap.Add("businessnumber", liushuinumber);
                paramMap.Add("transactionamount", jine);
                paramMap.Add("toaccountnumber", com_accountnumber);
                paramMap.Add("bankcode", "WXXCX");
                paramMap.Add("clientip", logip);
                paramMap.Add("merchtonline", "0");
                string type = "juhesell";
                if (comrcv.Map_Args.ContainsKey("type"))
                {
                    type = comrcv.Map_Args["type"];
                }
                Dictionary<string, string> appidsecret = GetAppidSecretDic(type);
                string wxappid = appidsecret["appid"];
                paramMap.Add("wxappid", wxappid);
                paramMap.Add("wxopenid", openid);


                string tf_sign = signForm(paramMap, sk);
                paramMap.Add("tf_sign", tf_sign);
                paramMap.Remove("dog_sk");
                string jsonStr = JsonConvert.SerializeObject(paramMap);
                string retsult = PostWebRequestForm(baseurl, paramMap);
                logJieKou.Info("聚合支付-" + companyname + "-传化接口返回-" + retsult);
                JObject retsultJson = JsonConvert.DeserializeObject(retsult) as JObject;
                string coderel = retsultJson["code"].ToString();
                string biz_code = retsultJson["biz_code"].ToString();
                string alldata = retsultJson["data"].ToString();
                if (coderel.Equals("GP_00") && biz_code.Equals("GPBIZ_00"))
                {
                    JObject alldataJson = JsonConvert.DeserializeObject(alldata) as JObject;
                    string htmldata = alldataJson["htmldata"].ToString();
                    logJieKou.Info("聚合支付-" + companyname + "-htmldata-" + htmldata);
                    htmldata = System.Web.HttpUtility.UrlDecode(htmldata);
                    logJieKou.Info("聚合支付-" + companyname + "-Decodehtmldata-" + htmldata);
                    //eyJhcHBJZCI6Ind4NTExMjFlYWE1YmY0NTg0YiIsInRpbWVTdGFtcCI6IjE1NzQ2NzM5ODgiLCJub25jZVN0ciI6ImZiMzI4NWM5ZmJmYzRhOWVhNTVkYTk5ZjMyNDgzN2U4IiwicGFja2FnZSI6InByZXBheV9pZD13eDI1MTcyNjI4NDI1MzI3NDEzM2UyN2ZlMDE1NzQxNzQ0MDAiLCJzaWduVHlwZSI6IlJTQSIsInBheVNpZ24iOiJjYnVidnNYTktDWE9lN0VuUWMzME1VNmxTT0hjQjhVT1JRRHJGd2xtRjltUDluZFVOUER0ZWpFRTB5ZC9kdFpPL0JOcXA1WVZHTWtSbnlBYmJETk84UGIyZDFhdmtmRDBESU01NW93a1hWTGxmek9GOXdPNzY3anpGQjRzRmNxN2F3Qk5JdlcrcTVZUzhxV3NWdm1HVXhycmNodWEzN2V5QndZdlFKNFJsWW5XTUE1M3VIa0wrT3ZlZ05YTnZjaDNyMHRzd251d0NxTkRLbzV4Q3Fha3ppeVBwUnNSb01aaHRyRVlFZ3FBV3J3ZGg3REI4UDhkRzBxYTdpWFA2UE1WbkpNSTU4QVYyRm1BM0tZWTc5QkpsYVVxNW02NFcrZkU4d05ON0ZZdnpJTUNwV081bVhmTlpyZkpmNHAybW44UFUyRXpUQTVVOXdDRHRyTGdyK1JYY1E9PSJ9
                    byte[] bytes = Convert.FromBase64String(htmldata);
                    try
                    {
                        htmldata = Encoding.GetEncoding("utf-8").GetString(bytes);

                        JObject htmldataalldata = JsonConvert.DeserializeObject(htmldata) as JObject;
                        ret.Map_Args["appId"] = htmldataalldata["appId"].ToString();
                        ret.Map_Args["timeStamp"] = htmldataalldata["timeStamp"].ToString();
                        ret.Map_Args["nonceStr"] = htmldataalldata["nonceStr"].ToString();
                        ret.Map_Args["package"] = htmldataalldata["package"].ToString();
                        ret.Map_Args["signType"] = htmldataalldata["signType"].ToString();
                        ret.Map_Args["paySign"] = htmldataalldata["paySign"].ToString();
                        //{"appId":"wx51121eaa5bf4584b","timeStamp":"1574674621","nonceStr":"a12ee6f6e9ef4ca282c3ce97f680c0e4","package":"prepay_id=wx25173701793032c0b595df511367595900","signType":"RSA","paySign":"XbB2DFpKmxDUc0ixIFo2RLkLQChB3niFeHkK6hcOzQlkOVEoBkI6iVawW1Z2sUIax3MFTsq02PLPbrddX6Vn5Wm56P/VCIdcsCV5G84niXABxGcdIUyQwcoPz7HtSMJ9FBi7jleMt4VPyPNGQ3rv074jMNjN/ZdtHikwhvxHBx1++CYjSv82Yj36f7oqY4jenHjQWyZxGIWdUmbLw7JHGwrdZecJluRCF0ApEj7P49JEj1VHCg/V2Nc6Rw/HDET40C0ftb/7sp4ybfQ9weLYx1Lcvjl+3VZoNnoNZz17L2e98vu6gA/XO6F4GrimlQax8+nMUBlyaUeU1/qHrbvyrg=="}
                    }
                    catch
                    {

                    }
                    logJieKou.Info("聚合支付结束-" + companyname + "-Base64htmldata-" + htmldata);
                }
                #endregion

                ret.Byte_Flag = (sbyte)1;

            }
            catch (Exception ex)
            {
                logJieKou.Info("聚合支付-" + ex.Message);
                mainsql.closesql();
                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        #endregion


        #region 聚合支付回调
        [WebMethod(Description = "正式版本")]
        public void ToMultiPayHui()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            logJieKou.Info("支付回调响应");
            string result = @"{ 
                     'result':'success',  
                     'msg':'请求成功'
                 }";
            JObject ret = JObject.Parse(result);

            #region 获取Post参数
            System.IO.Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            postContent = HttpUtility.UrlDecode(postContent);

            try
            {
                logJieKou.Info("支付回调结果：" + postContent);
                goto EXIT;
            }
            catch (Exception ex)
            {
                logJieKou.Info("支付回调Error：" + ex.Message);
            }
            #endregion
            EXIT:
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }

        #endregion

        #endregion


        #region 签名Form

        private string signForm(Dictionary<string, object> map, string secret)
        {
            if (map.ContainsKey("sign_type") && "RSA".Equals(map["sign_type"]))
            {
                return ZhiFuSignature.GetSignature("D:\\chuanhuafpx\\RSAJUHESHENG.pfx", "juhesheng01", map);
            }
            else
            {
                map.Add("dog_sk", secret);
                string[] key = map.Keys.ToArray<string>();
                Array.Sort(key, string.CompareOrdinal);
                StringBuilder sb = new StringBuilder();
                for (int i = key.Length - 1; i >= 0; i--)
                {
                    sb.Append(map[key[i]]);
                }
                string keyString = sb.ToString();
                MD5 md5 = MD5.Create();
                byte[] byteOld = Encoding.UTF8.GetBytes(keyString);
                byte[] byteNew = md5.ComputeHash(byteOld);

                string result = "";
                for (int i = 0; i < byteNew.Length; i++)
                {
                    long r = 0;
                    r = Convert.ToInt64(0x000000ff & byteNew[i]) | 0xffffff00;
                    result += r.ToString("X").Substring(6);
                }
                return result.ToUpper();
            }
        }
        #endregion

        #region PostWebRequestForm
        private string PostWebRequestForm(string postUrl, Dictionary<string, object> paramMap)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string ret = string.Empty;
            string paramData = "";
            int i = 0;
            StringBuilder builder = new StringBuilder();
            foreach (var item in paramMap)
            {
                if (i > 0)
                    builder.Append("&");
                if (paramMap.ContainsKey("sign_type") && "RSA".Equals(paramMap["sign_type"]))
                    builder.AppendFormat("{0}={1}", item.Key, System.Web.HttpUtility.UrlEncode(item.Value.ToString()));
                else
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            paramData = builder.ToString();
            logJieKou.Info("接口参数：" + paramData);
            if (paramData.Equals(""))
            {
                return ret;
            }

            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                logJieKou.Info("传化返回：" + ret);
                //ret = response.ResponseUri.AbsoluteUri;
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                logJieKou.Info(ex);
            }
            return ret;

        }

        #endregion


        #region JsonPostWebRequestForm
        private string JsonPostWebRequestForm(string postUrl, Dictionary<string, object> paramMap)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string ret = string.Empty;
            JObject job = new JObject();
            foreach (var item in paramMap)
            {
                job.Add(item.Key, item.Value.ToString());
            }
            var paraStr = JsonConvert.SerializeObject(job);
            logJieKou.Info("接口参数：" + paraStr);
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(paraStr); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/json";
                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                logJieKou.Info("传化返回：" + ret);
                //ret = response.ResponseUri.AbsoluteUri;
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                logJieKou.Info(ex);
            }
            return ret;

        }

        #endregion

        #region PostWebResponseUri
        private string PostWebResponseUri(string postUrl, Dictionary<string, object> paramMap)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string ret = string.Empty;
            string paramData = "";
            int i = 0;
            StringBuilder builder = new StringBuilder();
            foreach (var item in paramMap)
            {
                if (i > 0)
                    builder.Append("&");
                if (paramMap.ContainsKey("sign_type") && "RSA".Equals(paramMap["sign_type"]))
                    builder.AppendFormat("{0}={1}", item.Key, System.Web.HttpUtility.UrlEncode(item.Value.ToString()));
                else
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            paramData = builder.ToString();
            logJieKou.Info("接口参数：" + paramData);
            if (paramData.Equals(""))
            {
                return ret;
            }

            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                //ret = sr.ReadToEnd();
                ret = response.ResponseUri.AbsoluteUri;

                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                logJieKou.Info(ex);
            }
            return ret;

        }

        #endregion

    }
}